package com.szgd.service.sys;

import com.google.common.collect.Sets;
import com.szgd.service.personnel.PersonnelInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数.
 * 
 * @author calvin
 */
@Transactional(readOnly=true)
public class UserDetailsServiceImpl implements UserDetailsService {
	@Autowired
	private UserService userService;
	@Autowired
	private WfRoleService wfRoleService;
	@Autowired
	private PersonnelInfoService personnelInfoService;

	/**
	 * 获取用户Details信息的回调函数.
	 * 登录时候必须实现的函数，根据用户名取对象，赋给返回的UserDetails对象，spring-security会去判断密码
	 */
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		com.szgd.bean.User user = userService.getUserByLoginId(username);
		if (user == null) {
			throw new UsernameNotFoundException("用户" + username + " 不存在");
		}
		/*if (GlobalKeys.ENABLED_N.equals(user.getIsEnabled())) {
			throw new AuthenticationServiceException("用户" + username + " 已经停用");
		}*/
		String identityNo = user.getIdentityNo();
		boolean validate = true;
		String password = user.getUserPwd();
		/*
		if("UC".equals(userSource)){
			validate = false;//到大平台验证
			if(!validate){
				password = "failure";//验证失败，随便赋个密码，登录即失败
			}
			
		}else{
			
		}
		*/
		// -- 以下属性, 暂时全部设为true. --//
		boolean enabled = true;//user.getIsEnabled() == 1;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		String policeName = user.getUserName();// 关联的员工姓名
		List<Map<String, Object>> rightList = userService.findRoleRightListByLoginId(username, null, 1);
		String rileIds = wfRoleService.getWfRolesByUserId(user.getUserId());
		String siteIds = personnelInfoService.getSiteByUser(user.getUserId());
		String menuStr = "";
		Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user,rightList);
		UserDetails userdetails = new org.springframework.security.core.userdetails.User(user.getUserId(),user.getLoginId(),user.getLoginId(),
				password,user.getUserName(), menuStr, grantedAuths,
				rightList, user.getDeptCd(),user.getDeptParentId(), enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked,user.getDeptName(),identityNo,rileIds,siteIds,user.getPersonnelId());
		return userdetails;
	}

	/**
	 * 获得用户所有角色的权限集合.
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities(com.szgd.bean.User user, List<Map<String, Object>> rightList) {
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		authSet.add(new GrantedAuthorityImpl("ROLE_登录欢迎"));
		authSet.add(new GrantedAuthorityImpl("ROLE_修改密码"));
		authSet.add(new GrantedAuthorityImpl("ROLE_个人信息"));
		
		for(Map<String, Object> right : rightList){
			authSet.add(new GrantedAuthorityImpl((String) right.get("RIGHT_ID")));
		}
		
		 
		return authSet;
	}

	
	/**构建头部菜单
	 * @param rightList
	 * @return
	 */
	private String buildMenu(List<Map<String, Object>> rightList) {
		 /*
		  * <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown"><i
                 class="菜单样式[ICON_CLASS]"></i>1级菜单名称[RIGHT_NAME] <b class="caret"></b></a>
             <ul class="dropdown-menu">  <!--循环遍历取2级菜单-->
                 <li><a href="javascript:$.yf.link('访问地址[RIGHT_URL]')"><i class="菜单样式[ICON_CLASS]"></i>2级菜单名称[RIGHT_NAME]</a></li>
                 <li><a href="javascript:$.yf.link('访问地址[RIGHT_URL]')"><i class="菜单样式[ICON_CLASS]"></i>2级菜单名称[RIGHT_NAME]</a></li>
             </ul>
         </li>
         	如	
          	<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown"><i
	                            class="icon-th icon-white"></i>销售 <b class="caret"></b></a>
	            <ul class="dropdown-menu">
	            	<li><a href="javascript:$.yf.link('/biz/project/grid.do')"><i class="i-note"></i>销售项目列表</a></li>
	                <li><a href="javascript:$.yf.link('/biz/project/grid.do')"><i class="i-note"></i>项目进展总览</a></li>
	                <li><a href="javascript:$.yf.link('/biz/project/grid.do')"><i class="i-note"></i>客户档案管理</a></li>
	            </ul>
	        </li>
         */
		StringBuffer msg=new StringBuffer("");
	
		
		for(Map<String, Object>menu:rightList){
			if ( menu.get("PARENT_ID")==null||"".equals(String.valueOf(menu.get("PARENT_ID")))){ //一级菜单
				msg.append("<li class='dropdown'><a href='#' class='dropdown-toggle' data-toggle='dropdown'>");
				
				if(menu.get("ICON_CLASS")!=null&& !("".equals(String.valueOf(menu.get("ICON_CLASS"))))){
					msg.append("<i class='"+menu.get("ICON_CLASS")+"'></i>"+menu.get("RIGHT_NAME")+" <b class='caret'></b></a>");
				}else {
					msg.append(menu.get("RIGHT_NAME")+" <b class='caret'></b></a>");
				}
				
				
				int flag=0;  //标识是否有子集
				for(Map<String, Object>submenu:rightList){
					if(flag==0){
						msg.append(" <ul class='dropdown-menu'>");
					}
					if ( String.valueOf(menu.get("RIGHT_ID")).equals(String.valueOf(submenu.get("PARENT_ID")))){
						
						if(submenu.get("RIGHT_URL")!=null&&!("".equals(submenu.get("RIGHT_URL")))){
							msg.append("<li><a href=\"javascript:$.yf.linkToUrl('"+submenu.get("RIGHT_URL")+"')\"><i class='i-note'></i>"+submenu.get("RIGHT_NAME")+"</a></li>");
						}else {
							msg.append("<li class='dropdown-submenu'><a href='#' class='dropdown-toggle' data-toggle='dropdown'><i class='i-note'></i>");
							
							if(submenu.get("ICON_CLASS")!=null&& !("".equals(String.valueOf(submenu.get("ICON_CLASS"))))){
								msg.append("<i class='"+submenu.get("ICON_CLASS")+"'></i>"+submenu.get("RIGHT_NAME")+"</a>");
							}else {
								msg.append(submenu.get("RIGHT_NAME")+"</a>");
							}
							
							int subFlag=0; //表示是否有三级菜单
							for(Map<String, Object>submenu2:rightList){ //三级菜单
								if(subFlag==0){
									msg.append(" <ul class='dropdown-menu'>");
								}
								if(String.valueOf(submenu.get("RIGHT_ID")).equals(String.valueOf(submenu2.get("PARENT_ID")))){
									msg.append("<li><a href=\"javascript:$.yf.linkToUrl('"+submenu2.get("RIGHT_URL")+"')\"><i class='i-note'></i>"+submenu2.get("RIGHT_NAME")+"</a></li>");
								}
								subFlag++;
							}
							if(subFlag>0){
								msg.append("</ul>");
							}
							msg.append(" </li>");
						}
						
						/*else{//有三级菜单
							msg.append("<li class='dropdown'><a href='#' class='dropdown-toggle' data-toggle='dropdown'>");
							
							if(submenu.get("ICON_CLASS")!=null&& !("".equals(String.valueOf(submenu.get("ICON_CLASS"))))){
								msg.append("<i class='"+menu.get("ICON_CLASS")+"'></i>"+menu.get("RIGHT_NAME")+" <b class='caret'></b></a>");
							}else {
								msg.append(menu.get("RIGHT_NAME")+" <b class='caret'></b></a>");
							}
							
							int subFlag=0; //表示是否有三级菜单
							for(Map<String, Object>submenu2:rightList){ //三级菜单
								if(subFlag==0){
									msg.append(" <ul class='dropdown-menu'>");
								}
								if(String.valueOf(submenu.get("RIGHT_ID")).equals(String.valueOf(submenu2.get("PARENT_ID")))){
									msg.append("<li><a href=\"javascript:$.yf.linkToUrl('"+submenu2.get("RIGHT_URL")+"')\"><i class='i-note'></i>"+submenu2.get("RIGHT_NAME")+"</a></li>");
								}
								subFlag++;
							}
							if(subFlag>0){
								msg.append("</ul>");
							}
							msg.append(" </li>");
						}*/
						
						
						
					}
					flag++;
				}
				if(flag>0){
					msg.append("</ul>");
				}
				msg.append(" </li>");
				
			}
		}
		
		//System.out.println(msg.toString());
		
		return msg.toString();
	}

}
